<template>
  <div class="model-container">
    <h2>艺标文生成图</h2>
    <!-- 这里可以添加新建模型的表单或其他内容 -->
  </div>
  <div class="text-to-image-container">
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="input-section">
          <h3>正向提示词</h3>
          <el-input
            v-model="promptText"
            type="textarea"
            :rows="4"
            placeholder="请输入图片生成提示词..."
          />
          <div class="button-container">
            <el-button type="primary" @click="generateImage" :loading="isLoading">
              生成图片
            </el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="result-section">
          <h3>生成结果</h3>
          <div v-if="isLoading" class="loading-text"> 
            正在生成图片...
          </div>
          <div v-else-if="generatedImages.length === 0" class="no-result">
            等待生成结果...
          </div>
          <div v-else class="image-grid">
            <div v-for="(image, index) in generatedImages" :key="index" class="image-item">
              <el-image 
                :src="image.url" 
                fit="contain" 
                :preview-src-list="[image.url]"
                :initial-index="0"
                preview-teleported
              />
              <el-input
                v-model="image.customName"
                placeholder="请输入图片名称（可选）"
                size="small"
                clearable
              />
              <el-button 
                type="primary" 
                size="small" 
                class="save-button"
                @click="saveImageToDatabase(image.url, image.customName)"
              >
                保存图片
              </el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'TextToImageView',
  setup() {
    const baseUrl = 'http://localhost:8081'
    const promptText = ref('')
    const generatedImages = ref([])
    const isLoading = ref(false)

    // 生成唯一的文件名
    const generateUniqueFileName = () => {
      const timestamp = new Date().getTime()
      const random = Math.floor(Math.random() * 10000)
      return `text2img_${timestamp}_${random}.png`
    }

    // 保存图片到数据库
    const saveImageToDatabase = async (imageUrl, customName) => {
      try {
        // 使用自定义名称或默认名称
        const imageName = customName.trim() || '文生图'
        
        // 创建请求数据
        const requestData = {
          createimgName: imageName,
          createimgUrl: imageUrl
        }
        
        // 调用创建图片接口
        const response = await axios.post(baseUrl + '/AI/createimg', requestData)
        
        if (response.data.code === 200) {
          ElMessage.success('图片保存成功')
        } else {
          throw new Error(response.data.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error(error.message || '保存失败')
      }
    }

    const generateImage = async () => {
      if (!promptText.value.trim()) {
        ElMessage.warning('请输入提示词')
        return
      }

      isLoading.value = true
      generatedImages.value = []

      try {
        const response = await fetch('https://api.coze.cn/v1/workflow/stream_run', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer pat_haaRTZJHSmrrjNLA6dw1jPFN6MsattW9tiv0sTQ2sfUssCZ1McsrqFsn99KOp1WL'
          },
          body: JSON.stringify({
            parameters: {
              image_prompt: promptText.value
            },
            workflow_id: "7455613455479865370"
          })
        })

        const reader = response.body.getReader()
        const decoder = new TextDecoder()

        while (true) {
          const { done, value } = await reader.read()
          if (done) break

          const chunk = decoder.decode(value)
          const events = chunk.split('\n').filter(line => line.trim())

          for (const event of events) {
            if (event.startsWith('data:')) {
              try {
                const eventData = JSON.parse(event.slice(5))
                // Only process Message events with image_url
                if (eventData.content) {
                  const contentObj = JSON.parse(eventData.content)
                  if (contentObj.image_url) {
                    generatedImages.value.push({
                      url: contentObj.image_url,
                      customName: ''
                    })
                  }
                }
              } catch (e) {
                console.error('Error parsing event data:', e)
              }
            }
          }
        }

        if (generatedImages.value.length === 0) {
          ElMessage.warning('未获取到图片')
        } else {
          ElMessage.success('图片生成成功')
        }
      } catch (error) {
        console.error('生成失败:', error)
        ElMessage.error('图片生成失败')
      } finally {
        isLoading.value = false
      }
    }

    return {
      promptText,
      generatedImages,
      isLoading,
      generateImage,
      saveImageToDatabase
    }
  }
}
</script>

<style scoped>
.text-to-image-container {
  padding: 20px;
}

.input-section,
.result-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.button-container {
  margin-top: 16px;
  text-align: right;
}

.image-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 16px;
  justify-content: center;
  width: 100%;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  width: 200px;
}

.el-image {
  width: 200px;
  height: 200px;
  border-radius: 4px;
}

.save-button {
  width: 200px !important;
}

.loading-text,
.no-result {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.model-container {
  padding: 5px;
}

.el-input {
  margin: 8px 0;
}
</style>
